import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import qs from 'qs'

console.log(import.meta.env.VITE_API_DOMAIN)

const request = Axios.create({
  baseURL: import.meta.env.VITE_API_DOMAIN as string | undefined,
  timeout: 5000,
})

request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // eslint-disable-next-line no-param-reassign
    config.data = qs.stringify(config.data) // 转为 formdata 数据格式
    return config
  },
  (error: { message: string }) => {
    message.error(error.message)
  },
)

request.interceptors.response.use(
  (response: AxiosResponse): Promise<any> => {
    const { data } = response
    if (!data) {
      return Promise.reject(data)
    }

    return Promise.resolve(data)
  },
  (error: { message: string }) => {
    message.destroy()
    message.error('网络异常')
    return Promise.reject(error)
  },
)

request.get = (url: string, params?: object): Promise<any> =>
  request({
    method: 'get',
    url,
    params,
  })

request.post = (url: string, params?: object): Promise<any> =>
  request({
    method: 'post',
    url,
    data: params,
  })

export default request
